<script setup lang="ts">
import {ref} from 'vue'
import {watch} from "vue";
import Taskinput from "@/components/Taskinput.vue";
import Taskitem from "@/components/Taskitem.vue";
import type {ITaskItem} from "@/Types/ITaskItem";

let taskList = ref<ITaskItem []>([]); //{...}[] 对象数组

taskList.value = JSON.parse(window.localStorage.getItem('taskList')??"[]"); //调用JSON.parse实现反串行化，解析字符串为对象
watch(taskList, onSave, {deep:true}); //侦听taskList对象，一旦发生变化则调用onSave函数

function onAddTask(taskText: string){
  taskList.value.push({
    id:taskList.value.length + 1,
    text: taskText,
    isDone: false,
    isEdit: false
  });
}

function onSave(){
  window.localStorage.setItem('taskList', JSON.stringify(taskList.value)); //调用JSON.stringify实现串行化
}

function onDelete(item: ITaskItem){
  taskList.value = taskList.value.filter(it=>it!==item); //function checkItem(item: ITaskItem, it: ITaskItem){return it !== item;}
}
</script>

<template>
  <div class="container">
    <h1>ToDo List</h1>

    <Taskinput @addTask="onAddTask"></Taskinput> <!--子组件可通过事件向父组件传递消息-->

    <div class="task-list">
      <div v-for="item of taskList" class="task-item">
        <Taskitem :item="item" @onDelete="onDelete(item)"></Taskitem>
      </div>
    </div>
  </div>


</template>

<style scoped>
.container{
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 80%;
  margin: 0 auto;
  background-color: #f3f3f3;
}
h1{
  text-align: center;
  margin-top: 20px;
}

.task-list{
  padding: 0 2em;
}
.task-item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
}
</style>
